package com.link.base.base.serviceprojectnew.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.base.message.push.model.PushInfoInsert;
import com.link.base.base.message.push.service.PushService;
import com.link.base.basic.service.BasicCommonService;
import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.serviceprojectnew.model.Project;
import com.link.base.base.serviceprojectnew.model.ProjectReport;
import com.link.base.base.serviceprojectnew.model.ServiceProject;
import com.link.base.base.serviceprojectnew.service.ServiceProjectService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author unknown
 * @date unknown
 * @comments 项目
 */
@Controller
@RequestMapping("/link/ServiceProject")
public class ServiceProjectController extends BasicController<ServiceProject> {
    @Resource
    private ServiceProjectService serviceProjectService;
    @Resource
    private BasicCommonService basicCommonService;
    @Resource
    private PushService pushService;

    private static final Pattern PATTERN1 = Pattern.compile("\\[.*\\]");

    @Override
    public BasicService<ServiceProject> getBasicService() throws Exception {
        return serviceProjectService;
    }

    /**
     * 客户化导出.
     *
     * @param entity
     * @author unknown
     * @date 2019/2/28 11:25
     * @update yipeng.zhu@hand-china.com
     */
    @Override
    @RequestMapping(value = "/queryByExamplePage/exportData")
    @ResponseBody
    public Map<String, Object> exportData(ServiceProject entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.preDealSecurity(request);
            CoreUser user = UserUtil.getUser();
            if (null != user) {
                user.setExportType(qps.getExportFileType());
            }
            ExportWriter exportWriter;
            String exportType = "xlsx";
            if (exportType.equals(user.getExportType())) {
                exportWriter = ExportFactory.newExcelInstance(qps);
            } else {
                exportWriter = ExportFactory.newInstance(qps);
            }
            ServiceProject t = (ServiceProject) BasicModel.transformClass(entity.getClass(), qps);

            while (!qps.getStopExport()) {
                beforQueryAllOrExample(t, request);
                beforQueryExample(t, request);
                List<ServiceProject> list = getBasicService().queryByExamplePage(t);
                if (qps.getPage() == 1) {
                    qps.setTotal(t.getTotal());
                }
                t.setAttr4(user.getId().toString());
                exportWriter.wirteData(list);
                t.setPage(qps.getPage());
                t.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/resppersonlist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resppersonlist(@JsonParam ServiceProject serviceProject,
                                              @JsonParam QueryParams qps, HttpSession session, HttpServletRequest request,
                                              HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<User> list = null;
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            ServiceProject sp = (ServiceProject) BasicModel.transformClass(ServiceProject.class, qps);
            if (StringUtils.isNotBlank(serviceProject.getProjectId())) {
                sp.setProjectId(serviceProject.getProjectId());
            }
            System.out.println(sp.getOauth() + "###");
            //去掉安全性
            sp.setOauth(null);
            list = serviceProjectService.queryProjRespUserPage(sp);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) sp), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<User>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/srpropersonlist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> srpropersonlist(QueryParams qps, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            User u = (User) BasicModel.transformClass(User.class, qps);
            //去掉安全性
            u.setOauth(null);
            List<User> list = serviceProjectService.queryProjSrproUserPage(u);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) u), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<User>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 推送消息
     *
     * @throws Exception
     */
    @RequestMapping(value = "/pushmsg", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> pushMsg(ServiceProject entity, HttpSession session, HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        PushInfoInsert pushInfoInsert = new PushInfoInsert();
        String message = new String("[" + request.getParameter("loginName") + "@了你:] ");
        String rowStatus = request.getParameter("rowStatus");
        String status = basicCommonService.getLovByNameAndType("SERVICE_STATUS", request.getParameter("status"))
                .getName();
        String oldStatus = basicCommonService.getLovByNameAndType("SERVICE_STATUS", request.getParameter("oldStatus"))
                .getName();
        String priorityLevel = basicCommonService
                .getLovByNameAndType("SER_PRIORITY_LEVEL", request.getParameter("priorityLevel")).getName();
        String oldPriorityLevel = basicCommonService
                .getLovByNameAndType("SER_PRIORITY_LEVEL", request.getParameter("oldPriorityLevel")).getName();
        String severityLevel = basicCommonService
                .getLovByNameAndType("SER_SEVERITY_LEVEL", request.getParameter("severityLevel")).getName();
        String oldSeverityLevel = basicCommonService
                .getLovByNameAndType("SER_SEVERITY_LEVEL", request.getParameter("oldSeverityLevel")).getName();
        String newStr = "NEW";
        String update = "UPDATE";
        if (StringUtils.equals(rowStatus, newStr)) {
            message = message + "[" + request.getParameter("pFirstName") + "] 提出了新的任务: ["
                    + request.getParameter("abstracts") + "]";
            pushInfoInsert.setPushNote(message);
            List<Long> userList = new ArrayList<>();
            userList.add(Long.parseLong(request.getParameter("attr01")));
            pushInfoInsert.setUserList(userList);
            pushService.messageInsert(pushInfoInsert);
        } else if (StringUtils.equals(rowStatus, update)) {
            if (!(status.equals(oldStatus)) || !(priorityLevel.equals(oldPriorityLevel))
                    || !(severityLevel.equals(oldSeverityLevel))
                    || !request.getParameter("abstracts").equals(request.getParameter("oldAbstracts"))
                    || !request.getParameter("rFirstName").equals(request.getParameter("oldrFirstName"))) {
                message = message + "任务 [" + request.getParameter("oldAbstracts");
                String abstracts = "abstracts";
                String oldAbstracts = "oldAbstracts";
                if (!request.getParameter(abstracts).equals(request.getParameter(oldAbstracts))) {
                    message = message + "] 变成了 [" + request.getParameter("abstracts") + "]";
                }
                if (!(status.equals(oldStatus)) || !(priorityLevel.equals(oldPriorityLevel))
                        || !(severityLevel.equals(oldSeverityLevel))) {
                    if (!(status.equals(oldStatus))) {
                        message = message + " 状态由 [" + oldStatus + "] 变成了 [" + status + "]";
                    }
                    if (!(priorityLevel.equals(oldPriorityLevel))) {
                        message = message + " 优先级由 [" + oldPriorityLevel + "] 变成了 [" + priorityLevel + "]";
                    }
                    if (!(severityLevel.equals(oldSeverityLevel))) {
                        message = message + " 严重性由 [" + oldSeverityLevel + "] 变成了 [" + severityLevel + "]";
                    }
                }
                String rFirstName = "rFirstName";
                String oldrFirstName = "oldrFirstName";
                if (!request.getParameter(rFirstName).equals(request.getParameter(oldrFirstName))) {
                    message = message + " 责任人由 [" + request.getParameter("oldrFirstName") + "] 变成了 ["
                            + request.getParameter("rFirstName") + "]";
                }
                pushInfoInsert.setPushNote(message);
                String attr01 = "attr01";
                String attr03 = "attr03";
                if (request.getParameter(attr01).equals(request.getParameter(attr03))) {
                    pushInfoInsert.setUserId(Long.parseLong(request.getParameter("attr01")));
                    pushService.messageInsert(pushInfoInsert);
                } else {
                    List<Long> userList = new ArrayList<>();
                    userList.add(Long.parseLong(request.getParameter("attr01")));
                    userList.add(Long.parseLong(request.getParameter("attr03")));
                    pushInfoInsert.setUserList(userList);
                    pushService.messageInsert(pushInfoInsert);
                }
                result.put("success", true);
            }
        }
        return result;
    }

    /**
     * 判断是否过滤掉查询参数一一对应的数据个数都为0的
     * @author yipeng.zhu@hand-china.com
     * @param   entity
     * @param   filtes 查询条件
     * @return  true 可以过滤entity； false 不可以
     * @date 2019/3/21 17:18
     */
    public boolean isFiler(String[] filtes, ProjectReport entity) {
        if (filtes == null) {
            return false;
        }
        //筛选条件默认个数都为0
        boolean wholeZero = true;
        int num = 0;
        for (String str : filtes) {
            if (!wholeZero) {
                return wholeZero;
            }
            switch (str) {
                case "New":
                    if (entity.getNewBuild() > num) {
                        wholeZero = false;
                    }
                    break;
                case "DEVELOP_FININSH":
                    if (entity.getDevFinish() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Process":
                    if (entity.getProcess() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Test":
                    if (entity.getTest() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Closed":
                    if (entity.getClosed() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Cancelled":
                    if (entity.getCancelled() > num) {
                        wholeZero = false;
                    }
                    break;
                case "ReOpen":
                    if (entity.getReOpen() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Pendding":
                    if (entity.getPendding() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Delay":
                    if (entity.getDelay() > num) {
                        wholeZero = false;
                    }
                    break;
                case "waitReappear":
                    if (entity.getWaitReappear() > num) {
                        wholeZero = false;
                    }
                    break;
                case "testFail":
                    if (entity.getTestFail() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Confirm":
                    if (entity.getConfirm() > num) {
                        wholeZero = false;
                    }
                    break;
                case "Assigned":
                    if (entity.getAssigned() > num) {
                        wholeZero = false;
                    }
                    break;
                default:
                    break;
            }
        }
        return wholeZero;
    }

    /**
     * 对filtersRaw过滤解析 获取(快速查询)类型为status的查询参数
     * @author yipeng.zhu@hand-china.com
     * @param qps
     * @return filters 查询条件数组
     * @date 2019/3/21 17:26
     */
    public String[] resFiltersRaw(QueryParams qps) {
        JSONArray jsonArray = JSONObject.parseArray(qps.getFiltersRaw());
        //筛选条件值
        String selectValue = "";
        String[] filters = null;
        String selectType = "status";
        for (int i = 0; i < jsonArray.size(); i++) {
            String propery = ((JSONObject) jsonArray.get(i)).get("id").toString();
            if (selectType.equals(propery)) {
                selectValue = ((JSONObject) jsonArray.get(i)).get("value").toString();
                break;
            }
        }
        if (StringUtils.isNotBlank(selectValue)) {
            Matcher matcher = PATTERN1.matcher(selectValue);
            if (matcher.find()) {
                String matchValueRaw = matcher.group();
                matchValueRaw = matchValueRaw.substring(1, matchValueRaw.length() - 1);
                filters = matchValueRaw.split(",");
            } else {
                filters = selectValue.split(",");
            }
        }
        return filters;
    }

    @RequestMapping(value = "/queryProjStatusReport")
    @ResponseBody
    public Map<String, Object> queryProjStatusReport(@JsonParam QueryParams qps, @JsonParam ServiceProject entity, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<String, String>();
        //存放合并相同责任人后的数据
        List<ProjectReport> newList = new ArrayList<ProjectReport>();
        List<ProjectReport> projReportList;
        StringBuilder html = new StringBuilder("");
        StringBuilder title = new StringBuilder("");
        int newBuild = 0;
        int process = 0;
        int test = 0;
        int cancelled = 0;
        int pendding = 0;
        int reopen = 0;
        int closed = 0;
        int delay = 0;
        int devFinish = 0;
        int waitReappear = 0;
        int testFail = 0;
        int noStatus = 0;
        int assigned = 0;
        int confirm = 0;
        int totalCount = 0;
        try {
            qps.preDealSecurity(request);
            String[] filters = resFiltersRaw(qps);
            ServiceProject sp = (ServiceProject) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(sp, request);
            beforQueryExample(sp, request);
            if (StringUtils.isNotBlank(request.getParameter("usercorpid"))) {
                sp.setCorpid(Long.parseLong(request.getParameter("usercorpid")));
            }
            sp.setPageFlag(false);
            //已将条件语句sql写入xml，无需加到外部
            projReportList = serviceProjectService.queryProjStatusReport(sp);
            //合并责任人一样的数据
            for (int i = 0; i < projReportList.size(); i++) {
                //获取责任人ID
                Long key = projReportList.get(i).getId();
                String old = map.get(key);
                if (old != null) {
                    map.put(key.toString(), old + "," + (i));
                } else {
                    map.put(key.toString(), "" + (i));
                }
            }
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = map.get(key);
                String[] a = value.split(",");
                int newBuild1 = 0;
                int process1 = 0;
                int test1 = 0;
                int cancelled1 = 0;
                int pendding1 = 0;
                int reopen1 = 0;
                int closed1 = 0;
                int delay1 = 0;
                int noStatus1 = 0;
                int devFinish1 = 0;
                int waitReappear1 = 0;
                int testFail1 = 0;
                int confirm1 = 0;
                int assigned1 = 0;
                for (int j = 0; j < a.length; j++) {
                    newBuild1 += projReportList.get(Integer.valueOf(a[j])).getNewBuild();
                    process1 += projReportList.get(Integer.valueOf(a[j])).getProcess();
                    test1 += projReportList.get(Integer.valueOf(a[j])).getTest();
                    closed1 += projReportList.get(Integer.valueOf(a[j])).getClosed();
                    cancelled1 += projReportList.get(Integer.valueOf(a[j])).getCancelled();
                    reopen1 += projReportList.get(Integer.valueOf(a[j])).getReOpen();
                    pendding1 += projReportList.get(Integer.valueOf(a[j])).getReOpen();
                    delay1 += projReportList.get(Integer.valueOf(a[j])).getDelay();
                    devFinish1 += projReportList.get(Integer.valueOf(a[j])).getDevFinish();
                    waitReappear1 += projReportList.get(Integer.valueOf(a[j])).getWaitReappear();
                    testFail1 += projReportList.get(Integer.valueOf(a[j])).getTestFail();
                    assigned1 += projReportList.get(Integer.valueOf(a[j])).getAssigned();
                    confirm1 += projReportList.get(Integer.valueOf(a[j])).getConfirm();
                    noStatus1 += projReportList.get(Integer.valueOf(a[j])).getNoStatus();
                }
                ProjectReport newProjectReport = new ProjectReport();
                newProjectReport.setId(Long.parseLong(key));
                newProjectReport.setFirstName(projReportList.get(Integer.valueOf(a[0])).getFirstName());
                newProjectReport.setNewBuild(newBuild1);
                newProjectReport.setProcess(process1);
                newProjectReport.setTest(test1);
                newProjectReport.setClosed(closed1);
                newProjectReport.setCancelled(cancelled1);
                newProjectReport.setReOpen(reopen1);
                newProjectReport.setPendding(pendding1);
                newProjectReport.setDelay(delay1);
                newProjectReport.setDevFinish(devFinish1);
                newProjectReport.setWaitReappear(waitReappear1);
                newProjectReport.setTestFail(testFail1);
                newProjectReport.setNoStatus(noStatus1);
                newProjectReport.setAssigned(assigned1);
                newProjectReport.setConfirm(confirm1);
                //得到新的集合
                newList.add(newProjectReport);

                newBuild += newBuild1;
                process += process1;
                test += test1;
                closed += closed1;
                cancelled += cancelled1;
                reopen += reopen1;
                pendding += pendding1;
                delay += delay1;
                devFinish += devFinish1;
                waitReappear += waitReappear1;
                testFail += testFail1;
                noStatus += noStatus1;
                assigned += assigned1;
                confirm += confirm1;
            }
            totalCount = newBuild + assigned + process + test + closed + cancelled + reopen + pendding + delay
                                  + devFinish + waitReappear + testFail + confirm;
            title.append("<div id=\"showTableDiv\" class=\"showTableDiv\">");
            title.append("<table id=\"ProjectReport-table\" style=\"height: 100%;\" keyFilterDiv=\"keyFilter\">");
            title.append("<tr class=\"titleTr\">");

            if (totalCount != 0) {
                title.append("<td width='100' class=\"titleTd\">合计(" + totalCount + ")个</td>");
            }
            if (newBuild != 0) {
                title.append("<td width='100' class=\"titleTd\">新建(" + newBuild + ")个</td>");
            }
            if (assigned != 0) {
                title.append("<td width='100' class=\"titleTd\">已分配(" + assigned + ")个</td>");
            }
            if (process != 0) {
                title.append("<td width='100' class=\"titleTd\">进行中(" + process + ")个</td>");
            }
            if (devFinish != 0) {
                title.append("<td width='100' class=\"titleTd\">开发完成(" + devFinish + ")个</td>");
            }
            if (test != 0) {
                title.append("<td width='100' class=\"titleTd\">待测试(" + test + ")个</td>");
            }
            if (closed != 0) {
                title.append("<td width='100' class=\"titleTd\">已完成(" + closed + ")个</td>");
            }
            if (cancelled != 0) {
                title.append("<td width='100' class=\"titleTd\">已取消(" + cancelled + ")个</td>");
            }
            if (reopen != 0) {
                title.append("<td width='100' class=\"titleTd\">重新打开(" + reopen + ")个</td>");
            }
            if (pendding != 0) {
                title.append("<td width='100' class=\"titleTd\">待讨论(" + pendding + ")个</td>");
            }
            if (delay != 0) {
                title.append("<td width='100' class=\"titleTd\">暂时关闭(" + delay + ")个</td>");
            }
            if (waitReappear != 0) {
                title.append("<td width='100' class=\"titleTd\">待重现(" + waitReappear + ")个</td>");
            }
            if (testFail != 0) {
                title.append("<td width='100' class=\"titleTd\">测试不通过(" + testFail + ")个</td>");
            }
            if (confirm != 0) {
                title.append("<td width='100' class=\"titleTd\">确认关闭(" + confirm + ")个</td>");
            }
            title.append("</tr>");

            for (int i = 0; i < newList.size(); i++) {
                boolean isFiter = isFiler(filters, newList.get(i));
                if (isFiter) {
                    continue;
                }
                html.append("<tr class=\"conTr\">");
                if (totalCount != 0) {
                    html.append("<td width='100' class=\"conTd\">(" + (i + 1) + ")" + newList.get(i).getFirstName() + "</td>");
                }
                if (newBuild != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getNewBuild() + "</td>");
                }
                if (assigned != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getAssigned() + "</td>");
                }
                if (process != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getProcess() + "</td>");
                }
                if (devFinish != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getDevFinish() + "</td>");
                }
                if (test != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getTest() + "</td>");
                }
                if (closed != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getClosed() + "</td>");
                }
                if (cancelled != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getCancelled() + "</td>");
                }
                if (reopen != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getReOpen() + "</td>");
                }
                if (pendding != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getPendding() + "</td>");
                }
                if (delay != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getDelay() + "</td>");
                }
                if (waitReappear != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getWaitReappear() + "</td>");
                }
                if (testFail != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getTestFail() + "</td>");
                }
                if (confirm != 0) {
                    html.append("<td width='100' class=\"conTd\">" + newList.get(i).getConfirm() + "</td>");
                }
                html.append("</tr>");
            }

            if (totalCount == 0) {
                html.append("<td class=\"conTdNone\">暂无数据</td>");
            }

            html = title.append(html);

            html.append("</table>");
            html.append("</div>");

            result.put("success", true);
            result.put("html", html);
            result.put("total", getCount((BasicModel) sp, totalCount));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("html", "");
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    @RequestMapping(value = "/preDefaultValue", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> preDefaultValue(@JsonParam ServiceProject entity, HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            result.put("success", true);
            result.put("result", getBasicService().preDefaultValue(entity));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    @Override
    protected void beforeImport(List<ServiceProject> list, QueryParams qps, HttpServletRequest request) throws Exception {
        //获取当前用户可选的项目
        CoreUser user = UserUtil.getUser();
        User u = new User();
        u.setId(user.getId());
        u.setPageFlag(false);
        List<Project> projList = new ArrayList<>();

        //项目名称，项目对象map缓存
        Map<String, Project> map = new HashMap<String, Project>();
        //项目名称，《用户名称，用户对象》Map
        Map<String, Map<String, User>> userMap = new HashMap<String, Map<String, User>>();
        for (int i = 0; list != null && i < list.size(); i++) {
            ServiceProject record = list.get(i);
            String projName = record.getProjName();

            //根据项目名称到map中找，没找到则到list中找并加入map缓存
            Project proj = map.get(projName);
            if (proj == null) {
                boolean found = false;
                for (Project p : projList) {
                    if (projName.equals(p.getProjName())) {
                        record.setProjectId(p.getId().toString());
                        map.put(projName, p);
                        found = true;
                        //获取该项目下对应人员并加到map中
                        Map<String, User> projUserMap = getProjUser(p.getId().toString());
                        userMap.put(projName, projUserMap);
                        proj = p;
                        break;
                    }
                }
                if (!found) {
                    map.put(projName, null);
                    throw new ServiceException("SERVICEREQUESTNEW-001", projName);
                }
            }
            //项目id
            record.setProjectId(proj.getId().toString());
            User rUser = userMap.get(projName).get(record.getrFirstName());
            Long rUserId = rUser == null ? 0L : rUser.getId();
            //责任人
            record.setResponserId(rUserId);
            User pUser = userMap.get(projName).get(record.getpFirstName());
            Long pUserId = pUser == null ? 0L : pUser.getId();
            //提出人
            record.setProposerId(pUserId);
        }
    }

    /**
     * <p>获取项目下的关联人员</p>
     * @author yrf
     * @param projId
     * @return
     */
    private Map<String, User> getProjUser(String projId) throws Exception {
        //User u = (User) BasicModel.transformClass(User.class, qps);
        ServiceProject sp = new ServiceProject();
        sp.setProjectId(projId);
        sp.setPageFlag(false);
        List<User> listUser = serviceProjectService.queryProjRespUserPage(sp);
        Map<String, User> map = new HashMap<String, User>();
        for (User user : listUser) {
            map.put(user.getFirstName(), user);
        }
        return map;
    }

    /**
     * 任务反馈新建
     *
     * @param entity
     * @author jiangtao
     * @date 2019/3/7 上午9:38
     */
    @RequestMapping(value = "/insertMission")
    @ResponseBody
    public Map<String, Object> insertMission(@JsonParam ServiceProject entity, HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            serviceProjectService.insertMission(entity);
            ServiceProject newEntry = this.getBasicService().queryById(entity);
            result.put("success", true);
            result.put("newRow", newEntry);
            result.put("code", "200");
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }

        return result;
    }

    /**
     * 以任务状态为未读统计当前用户的任务数量
     *
     * @author xieyuqiang
     * @date 2019/3/27 10:41
     * @param entity 任务对象实体，用于接收筛选参数等
     */
    @RequestMapping(value = "/taskNumberCountByStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> taskNumberCountByStatus(@JsonParam ServiceProject entity, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {

            List<ServiceProject> taskList = serviceProjectService.taskNumberCountByStatus(entity);

            result.put("rows", taskList);
            result.put("success", true);
            result.put("code", "200");
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 其他系统任务反馈创建
     *
     * @author 李莹
     * @date 2019/12/20 02:06
     * @param entity 任务对象实体，用于接收反馈数据
     */
    @RequestMapping(value = "/openInsertFeedback", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> openInsertFeedback(@JsonParam ServiceProject entity, HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {

            ServiceProject newEntry = serviceProjectService.openInsertFeedback(entity);

            result.put("success", true);
            result.put("newRow", newEntry);
            result.put("code", 200);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
        }

        return result;
    }
}
